/*
 * @Author: Wangjun
 * @Date: 2023-08-14 10:40:47
 * @LastEditTime: 2023-12-11 21:09:19
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \xr_node_calc\noderdb\op_di.go
 * hnxr
 */
package noderdb

import (
	"errors"

	"gitee.com/haodreams/op_node/thirdparty"
	"gitee.com/hnxr_1/lib/device"
	"gitee.com/hnxr_1/nodex"
)

func init() {
	nodex.Reister(new(DI))
}

type DI struct {
	nodex.Node
	Y    nodex.Boolean `remark:"输出Y,,out"`
	item *thirdparty.Item
	Tag  string
	Kind string //类别
}

func (m *DI) GetModelID() int {
	return nodex.ModIn
}

func (m *DI) GetName() string {
	return "DI"
}

func (m *DI) Init(mem *nodex.Memory) (err error) {
	extends := m.GetExtends()
	parent := m.GetParent()
	atag := extends["tag"]
	tag, _ := atag.(string)
	acategory := extends["category"]
	category, _ := acategory.(string)
	if tag != "" {
		m.Tag = tag
		m.Kind = category
		m.item = dataitem.GetMemItem(category, parent.RID, tag)
	}

	return
}

/**
 * @description: 节点信息
 * @return {*}
 */
func (m *DI) RegData() []byte {
	return nodex.MakeRegData(m, "内存开关量输入", m.GetName(), "")
}

func (m *DI) Calc() (err error) {
	// parent := m.GetParent()
	// if m.Parent.RID == 316 {
	// 	log.Println(m.Tag, m.item.V, m.item.Q)
	// }
	if m.item == nil {
		m.Bad = true
		m.Err = errors.New(m.Tag + ":测点不存在")
		if m.EnQ {
			return m.Err
		}
		return
	}
	if m.item.Q == device.QNull {
		m.Err = errors.New(m.Tag + ":测点不存在")
		m.Bad = true
		if m.EnQ {
			return m.Err
		}
		return
	}
	m.Y.Value = int(m.item.V) != 0
	m.Bad = false
	//fmt.Printf("DI:%p\n", m.Y.BoolValue)
	return
}
